package com.tools.elk;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class InsertES {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("user").id("1000");
        User user = new User();
        user.setAddress("张家洼");
        user.setName("王常风");
        user.setAge(32);
        //向es插入数据只能是json格式
        String userJson = JSONObject.toJSONString(user);

        indexRequest.source(userJson, XContentType.JSON);

        IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(index.getResult());

        client.close();


    }
}
